﻿Imports System
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Media
Imports System.Windows.Media.Imaging
Imports System.Collections.Generic


Public Class ImageManager

    Private Shared ReadOnly _converterUri As String = Nothing
    Shared Sub New()
        ImageManager._converterUri = TryCast(Application.Current.Resources("ImageConverterUri"), String)
    End Sub

#Region "Dependency Properties"
    Public Shared ReadOnly ImageSourceProperty As DependencyProperty = _
        DependencyProperty.RegisterAttached("ImageSource", GetType(ImageSource), _
                                            GetType(ImageManager), _
                                            New PropertyMetadata(New PropertyChangedCallback( _
                                                                 AddressOf ImageManager.OnImageSourceChanged)))
    Public Shared Function GetImageSource(ByVal obj As DependencyObject) As ImageSource
        Return obj.GetValue(ImageManager.ImageSourceProperty)
    End Function
    Public Shared Sub SetImageSource(ByVal obj As DependencyObject, ByVal source As ImageSource)
        obj.SetValue(ImageManager.ImageSourceProperty, source)
    End Sub
#End Region
    Private Shared Sub OnImageSourceChanged(ByVal obj As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs)
        Dim img = TryCast(obj, Image)
        If Object.ReferenceEquals(Nothing, img) Then
            Return
        End If
        Dim src = ImageManager.GetImageSource(obj)
        If Object.ReferenceEquals(Nothing, src) Then
            Return
        End If
        Dim bi = TryCast(src, BitmapImage)
        If Not Object.ReferenceEquals(Nothing, bi) Then
            Dim uri = bi.UriSource
            If uri.IsAbsoluteUri Then
                If Not String.IsNullOrEmpty(ImageManager._converterUri) Then
                    Dim isOk = True
                    If uri.OriginalString.Contains(".gif") Then
                        isOk = False
                    End If
                    If Not isOk Then
                        bi.UriSource = New Uri(String.Format(ImageManager._converterUri, uri.AbsoluteUri), UriKind.Absolute)
                    End If
                End If
            End If
        End If
        img.Source = src
    End Sub
End Class